package com.css.spring.formework.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class AopProxy implements InvocationHandler {

    private Object target;
    private AopConfig aopConfig;


    public Object getProxy(Object instance) {

        this.target = instance;

        Class<?> aClass = instance.getClass();

        return Proxy.newProxyInstance(aClass.getClassLoader(), aClass.getInterfaces(), this);
    }

    public AopConfig getAopConfig() {
        return aopConfig;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method method1 = this.target.getClass().getMethod(method.getName(), method.getParameterTypes());
        if (aopConfig.contains(method1)) {
            AopConfig.Aspect aspect = aopConfig.get(method1);
            Method[] points = aspect.getPoints();
            if (points.length > 0) {
                points[0].invoke(aspect.getAspect());
            }
        }

        Object invoke = method.invoke(this.target, args);

        if (aopConfig.contains(method1)) {
            AopConfig.Aspect aspect = aopConfig.get(method1);
            Method[] points = aspect.getPoints();
            if (points.length > 1) {
                points[1].invoke(aspect.getAspect());

            }
        }

        return invoke;
    }

    public void setAopConfig(AopConfig aopConfig) {
        this.aopConfig = aopConfig;
    }
}
